package com.common.util;

import com.alibaba.fastjson.JSONObject;
import com.common.base.BaseEnum;
import com.common.vo.MessageLogVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import javax.annotation.Resource;
import java.time.LocalDateTime;


/**
 * @version: V1.0
 * @author: szw
 * @className: MsgSendUtil
 * @packageName: MsgSendUtil
 * @description: 发消息工具类
 * @data: 2021-1-27
 **/
@Component
@Slf4j
public class MsgSendUtil {

    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;



    /**
     * 发送消息核心方法
     *
     * @param topic
     * @param obj
     */
    public void send(String url, String topic, Object obj) {
        String data = JSONObject.toJSONString(obj);
        log.info("准备发送消息为：{}", data);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, data);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info(topic + " - 生产者 发送消息失败：" + throwable.getMessage());
                DingDingUtils.sendTextToDD("警告：kafka服务者发送消息失败，错误信息"+throwable.getMessage());
                mesLog(url, topic, data, throwable.getMessage(), 1);
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(topic + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
                mesLog(url, topic, data, stringObjectSendResult.toString(), 0);
            }
        });
    }

    /**
     * 异步发送消息
     * @param url
     * @param topic
     * @param obj
     */
    public void asyncSend(String url, String topic, MessageLogVo  obj) {
        String data = JSONObject.toJSONString(obj);
        log.info("准备异步发送消息为：{}", data);
        //发送消息
        kafkaTemplate.send(topic, data).addCallback(success -> {
            //成功的处理
            int partition = success.getRecordMetadata().partition();
            // 消息在分区内的offset
            long offset = success.getRecordMetadata().offset();
            log.info(topic + " - 生产者 异步发送消息成功：分区：" + partition + "-" + offset);
            obj.setMesStatus(0);
            obj.setMesResult(String.valueOf(offset));
            mesUpdateLog(url,obj);
        }, failure -> {
            //发送失败的处理
            log.error(topic + " - 生产者 异步发送消息失败：" + failure.getMessage());
            DingDingUtils.sendTextToDD("警告：kafka服务者异步发送消息失败，错误信息"+failure.getMessage());

        });
    }

    /**
     * 记录发送消息信息
     *
     * @param topic
     * @param data
     * @param result
     * @param status
     */
    private void mesLog(String url, String topic, String data, String result, Integer status) {
        MessageLogVo messageLogVo = MessageLogVo.builder()
                .created(BaseEnum.ADMIN.getCode()).mesStatus(status)
                .mesBody(data).mesResult(result).mesTopic(topic)
                .createdDate(LocalDateTime.now()).mesType(0)
                .build();
        RestTemplateUtil.post(url + "/message/save", messageLogVo, JSONObject.class);
    }


    /**
     * 更新发送消息信息
     * @param obj
     */
    private void mesUpdateLog(String url,MessageLogVo obj) {
        RestTemplateUtil.post(url + "/message/update", obj, JSONObject.class);
    }
}
